package com.ln.store.web.servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ln.store.domain.Category;
import com.ln.store.service.CategoryService;
import com.ln.store.service.Impl.CategoryServiceImpl;
import com.ln.store.utils.JedisUtils;
import com.ln.store.web.base.BaseServlet;

import net.sf.json.JSONArray;
import redis.clients.jedis.Jedis;

/**
 * Servlet implementation class CategoryServlet
 */
public class CategoryServlet extends BaseServlet {
	
	/**
	 * 获取全部分类
	 * @param request
	 * @param response
	 * @return
	 */
	public String findCategory(HttpServletRequest request,HttpServletResponse response) {
		try {
			//在redis中获取全部分类信息
			Jedis jedis = JedisUtils.getJedis();
			String jsonStr = jedis.get("allCats");
			if (jsonStr == null || jsonStr.equals("")) {
				//调用业务层：获取全部分类信息，返回集合
				CategoryService service = new CategoryServiceImpl();
				List<Category> list = service.getAllCats();
			    jsonStr = JSONArray.fromObject(list).toString();
				//将获取到的JSON格式的数据存入redis
				jedis.set("allCats",jsonStr);
				//将全部分类信息响应到客户端
				response.setContentType("application/json;charset=utf-8");
				response.getWriter().print(jsonStr);
				//System.out.println("没有缓存数据");
			}else {
				//System.out.println("缓存数据");
				//将全部分类信息响应到客户端
				response.setContentType("application/json;charset=utf-8");
				response.getWriter().print(jsonStr);	
			}
			//转发到真实的首页
			return null;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
}
